package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created by phazel on 17/04/14.
 */
public class UserAuthenticator
{
    ArrayList<User> users = new ArrayList<User>();
    Scanner kb;
    User currentUser = null;

    public UserAuthenticator( Scanner kb )
    {
        this.kb = kb;
        createUsers();
    }

    private void createUsers()
    {
        users.add(new User("Joe Blogs", "999-0000", "elephant"));
        users.add( new User( "Jane Doe" , "555-0000", "dinosaur" ) );
    }

    public void login()
    {
        System.out.print("Enter your library number (format XXX-XXXX) : ");
        String libraryNumberInput = kb.nextLine();

        User user = findUser( libraryNumberInput );

        if( user != null )
        {
            checkPassword( user );
        }
    }

    public User getCurrentUser()
    {
        return currentUser;
    }

    private User findUser( String libraryNumberInput )
    {
        User found = null;

        for( User user: users )
        {
            if( user.getLibraryNumber().equals( libraryNumberInput ) )
            {
                found = user;
                break;
            }
        }

        return found;
    }

    private void checkPassword( User user )
    {
        System.out.print( "Enter your password : " );
        String passwordInput = kb.nextLine();

        if( user.getPassword().equals( passwordInput ) )
        {
            currentUser = user;
            greetUser( currentUser );
        }
    }

    private void greetUser( User user )
    {
        System.out.println( "Welcome, " + user.getName() + "!" );
    }
}
